﻿using Microsoft.AspNetCore.Mvc;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using ProjectScheduling_web.dao;
using ProjectScheduling_web.model;
using ProjectScheduling_web.pagemodel;
using SqlSugar;
using System.Data;

namespace ProjectScheduling_web.Controllers.U
{
    [ApiController]
    public class PropareController : BController
    {
        private static readonly ProjectsDao @base = ProjectsDao.Base;
        [HttpGet]
        public ActionResult GetTypes()
        {
            var list = ProjectTypesDao.Base.FindAll(it => true);
            return Success(list);
        }
        [HttpPost]
        public ActionResult Search(SearchModel req)
        {
            if (req == null) return Fail("参数错误");
            var start = req.Start ?? DateTime.MinValue;// req.Start.HasValue ? req.Start.Value : DateTime.MinValue;
            var end = req.End.HasValue ? req.End.Value.AddDays(1) : DateTime.MaxValue;
            if (HttpContext.Items["Current_Msg"] is not Member mem) return Fail("获取登录状态有误");
            var datas = @base.FindAll(req.Page, req.Row, it => (mem.IsAdmin == true || it.SalespersonId == mem.Id) &&
            it.CreateDate > start && it.CreateDate < end &&
            (string.IsNullOrEmpty(req.Key) || !string.IsNullOrEmpty(it.Name) && it.Name.Contains(req.Key)) &&
            (req.State == 0 || it.State == req.State)
            );
            return Success(datas);
        }
        [HttpPost]
        public ActionResult Add(Projects req)
        {
            if (HttpContext.Items["Current_Msg"] is not Member mem) return Fail("获取登录状态有误");
            if (req.Id == 0)
            {
                req.SalespersonId = mem.Id;
                req.CreateDate = DateTime.Now;
                req.State = Enum_ProjectState.待排期;
                @base.Add(req);
                return Success("报备成功");
            }
            else
            {
                @base.Update(req, it => new
                {
                    it.ProjectTypeId,
                    it.CustomerName,
                    it.Linker,
                    it.Phone,
                    it.Name,
                    it.Address,
                    it.ContractState,
                    it.ApproveState,
                    it.PlanStartDate,
                    it.Description,
                    it.OwnerShip
                });
                return Success("修改成功");
            }
        }
        [HttpGet("/propare/find/{id}")]
        public ActionResult Find(int id)
        {
            var obj = @base.Find(id);
            return obj == null ? Fail(obj) : Success(obj);
        }
        [HttpDelete("/propare/delete/{id}")]
        public ActionResult Delete(int id)
        {
            var obj = @base.Find(id);
            if (obj == null) return Fail("删除失败，当前项目不存在");
            if (obj.State != Enum_ProjectState.待排期) return Fail("只能删除待排期的项目");
            @base.Delete(id);
            return Success("删除成功");
        }
        /// <summary>
        /// 分组信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult GroupData()
        {
            if (HttpContext.Items["Current_Msg"] is not Member mem) return Fail("获取登录状态有误");
            return Success(@base.GroupMsg(mem.IsAdmin ? 0 : mem.Id));
        }
        /// <summary>
        /// 待排期
        /// </summary>
        /// <returns></returns>
        [HttpGet("/propare/homelist/{state}/{count}")]
        public ActionResult HomeList(Enum_ProjectState state, int count)
        {
            if (HttpContext.Items["Current_Msg"] is not Member mem) return Fail("获取登录状态有误");
            var datas = @base.FindAll(it => (mem.IsAdmin == true || it.SalespersonId == mem.Id) && it.State == state, count);
            return Success(datas);
        }
        [HttpPost("/propare/export")]
        public ActionResult ExportExcel(SearchModel req)
        {
            var start = req.Start.HasValue ? req.Start.Value : DateTime.MinValue;
            var end = req.End.HasValue ? req.End.Value.AddDays(1) : DateTime.MaxValue;
            if (HttpContext.Items["Current_Msg"] is not Member mem) return Fail("获取登录状态有误");
            var datas = @base.FindAll(it => (mem.IsAdmin == true || it.SalespersonId == mem.Id) &&
            it.CreateDate > start && it.CreateDate < end &&
            (string.IsNullOrEmpty(req.Key) || !string.IsNullOrEmpty(it.Name) && it.Name.Contains(req.Key)) &&
            //it.State != 0 && it.State != Enum_ProjectState.待排期
            (req.State == 0 || it.State == req.State)
            );
            // 创建工作簿
            IWorkbook workbook = new XSSFWorkbook();
            ISheet sheet = workbook.CreateSheet("Sheet1");


            // 创建表头
            IRow headerRow = sheet.CreateRow(0);
            headerRow.Height = 400;
            var font = workbook.CreateFont();
            font.IsBold = true;
            ICell hc(int index)
            {
                var cell = headerRow.CreateCell(index);
                cell.CellStyle.SetFont(font);
                return cell;
            }
            hc(0).SetCellValue("项目名称");
            headerRow.CreateCell(1).SetCellValue("销售人员");
            headerRow.CreateCell(2).SetCellValue("项目归属");
            headerRow.CreateCell(3).SetCellValue("项目类型");
            headerRow.CreateCell(4).SetCellValue("施工人员");
            headerRow.CreateCell(5).SetCellValue("客户名称");
            headerRow.CreateCell(6).SetCellValue("联系人");
            headerRow.CreateCell(7).SetCellValue("联系电话");
            headerRow.CreateCell(8).SetCellValue("合同时间");
            headerRow.CreateCell(9).SetCellValue("地址");
            headerRow.CreateCell(10).SetCellValue("合同情况");
            headerRow.CreateCell(11).SetCellValue("审批情况");
            headerRow.CreateCell(12).SetCellValue("进度");
            headerRow.CreateCell(13).SetCellValue("人天消耗");
            headerRow.CreateCell(14).SetCellValue("状态");
            headerRow.CreateCell(15).SetCellValue("报备时间");
            headerRow.CreateCell(16).SetCellValue("实际开始时间");
            headerRow.CreateCell(17).SetCellValue("实际结束时间");
            headerRow.CreateCell(18).SetCellValue("实际周期（天）");
            headerRow.CreateCell(19).SetCellValue("投入人数");
            var lineId = 1;
            datas.ForEach(item =>
            {
                // 写入数据行
                IRow dataRow = sheet.CreateRow(lineId);
                dataRow.CreateCell(0).SetCellValue(item.Name);
                dataRow.CreateCell(1).SetCellValue(item.SaleMsg?.Name);
                dataRow.CreateCell(2).SetCellValue(item.OwnerShip);
                dataRow.CreateCell(3).SetCellValue(item.ProjectType?.Name);
                var staffNames = string.Join('、', item.StaffsList?.Select(it => it.UserName) ?? []);
                new Action(() =>
                {
                    var dt = @base.ToTable("SELECT a.TrueName FROM Staff a INNER JOIN (SELECT DISTINCT b.StaffId AS SId FROM PreparedData a INNER JOIN PreparedStaff b ON a.Id=b.PreparedId WHERE a.ProjectId=@id) b ON a.Id=b.SId", ("@id", item.Id));
                    if (dt.Rows.Count > 0)
                    {
                        staffNames = string.Join('、', dt.Rows.Cast<DataRow>().Select(it => it[0].ToString()));
                    }
                })();
                dataRow.CreateCell(4).SetCellValue(staffNames);
                dataRow.CreateCell(5).SetCellValue(item.CustomerName);
                dataRow.CreateCell(6).SetCellValue(item.Linker);
                dataRow.CreateCell(7).SetCellValue(item.Phone);
                dataRow.CreateCell(8).SetCellValue(item.PlanStartDate.ToString("yyyy-MM-dd日"));
                dataRow.CreateCell(9).SetCellValue(item.Address);
                dataRow.CreateCell(10).SetCellValue(item.ContractState);
                dataRow.CreateCell(11).SetCellValue(item.ApproveState);
                dataRow.CreateCell(12).SetCellValue(item.Rate);
                if (item.PreparedDatas != null)
                {
                    var days = PreparedDataDao.Base.FindAll(it => it.ProjectId == item.Id).Sum(it => it.PrepardStaffs?.Sum(z => z.Days));
                    dataRow.CreateCell(13).SetCellValue(days.ToString());
                }
                else
                {
                    dataRow.CreateCell(13).SetCellValue("");
                }

                dataRow.CreateCell(14).SetCellValue(item.State.ToString());
                dataRow.CreateCell(15).SetCellValue(item.CreateDate.ToString("yyyy-MM-dd HH:mm:ss"));
                dataRow.CreateCell(16).SetCellValue(item.FromDate.ToString("yyyy-MM-dd"));
                dataRow.CreateCell(17).SetCellValue(item.State == Enum_ProjectState.已完结 ? item.ToDate.ToString("yyyy-MM-dd") : "");
                //var t = ProjectsDao.Base.ToTable("SELECT SUM(a.Days) FROM PreparedData a WHERE a.ProjectId=@id", ("@id", item.Id));
                var t = 0;
                if (item.State == Enum_ProjectState.已完结 && item.FromDate > DateTime.Parse("2024-01-01") && item.ToDate > DateTime.Parse("2024-01-01"))
                {
                    t = (int)(item.ToDate.Date - item.FromDate.Date).TotalDays + 1;
                }
                dataRow.CreateCell(18).SetCellValue(t);
                var t1 = @base.ToTable("SELECT COUNT(DISTINCT b.StaffId) FROM PreparedData a INNER JOIN PreparedStaff b ON a.Id=b.PreparedId WHERE a.ProjectId=@id", ("@id", item.Id));
                dataRow.CreateCell(19).SetCellValue(t1.Rows.Count > 0 ? t1.Rows[0][0].ToString() : item?.StaffsList?.Count.ToString());
                lineId++;
            });


            // 设置列宽
            sheet.SetColumnWidth(0, 30 * 256);
            sheet.SetColumnWidth(3, 15 * 256);
            sheet.SetColumnWidth(4, 30 * 256);
            sheet.SetColumnWidth(5, 30 * 256);

            sheet.SetColumnWidth(7, 20 * 256);
            sheet.SetColumnWidth(8, 15 * 256);
            sheet.SetColumnWidth(9, 10 * 256);
            sheet.SetColumnWidth(10, 15 * 256);
            sheet.SetColumnWidth(11, 15 * 256);
            sheet.SetColumnWidth(15, 30 * 256);
            using var memory = new MemoryStream();
            workbook.Write(memory);
            var content = memory.ToArray();
            return File(content, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "output.xlsx");
        }
    }
}
